package club.babyf.nativeai.demo.algorithm;

/**
 * _18_BinarySearch.
 *
 * @author zhanglei.
 * @date 2025/7/20 18:33.
 * @description 二分查找法.
 */
public class _18_BinarySearch {

    public int binarySearch(int[] arr, int target) {
        int left = 0;
        int right = arr.length - 1;
        while (left <= right) {
            int mid = left + (right - left) / 2;
            if (arr[mid] == target) {
                return mid;
            } else if (arr[mid] < target) {
                left = mid + 1;
            } else {
                right = mid - 1;
            }
        }
        return -1;
    }

    public static void main(String[] args) {
        _18_BinarySearch binarySearch = new _18_BinarySearch();
        int[] arr = {1, 2, 3, 4, 5, 6, 7, 8};
        int i = binarySearch.binarySearch(arr, 6);
        System.out.println(i);
    }

}
